package net.sourceforge.jweb.util;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import freemarker.cache.NullCacheStorage;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FreeMarkerUtil {
	private static final String base = "/freemarker/";
	private final static Logger LOGGER = LoggerFactory.getLogger(FreeMarkerUtil.class);
	@SuppressWarnings("deprecation")
	private final static Configuration freemarkerCfg = new Configuration();
	static {
		try {
			freemarkerCfg.setClassForTemplateLoading(FreeMarkerUtil.class, base);
			freemarkerCfg.setEncoding(Locale.getDefault(), "UTF-8");
			freemarkerCfg.setCacheStorage(new NullCacheStorage());
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private FreeMarkerUtil() {
	}

	public static String processTemplate(String name, Map<String, Object> param) {
		// LOGGER.debug("processinng "+name+" with "+param);
		try {
			Writer writer = new StringWriter();
			Template template = freemarkerCfg.getTemplate(name);
			template.process(param, writer);

			return writer.toString();
		} catch (IOException e) {
			String stack = ExceptionBuilder.buildStack(e);
			LOGGER.error(stack);
			return stack;
		} catch (TemplateException e) {
			String stack = ExceptionBuilder.buildStack(e);
			LOGGER.error(stack);
			return stack;
		}
	}

	public static String processTemplate(String templateName, Object... params) {
		Map<String, Object> model = new HashMap<String, Object>();
		for (int i = 0; i < params.length;) {
			model.put(params[i++].toString(), params[i++]);
		}
		return FreeMarkerUtil.processTemplate(templateName, model);
	}
}
